<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Controller App
 *
 * @author luubk
 * @since 12-06-2012 - 01:13:26
 */
class Apps extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        $this->load->model('m_app');
        $this->load->model('m_app_cate');
        $this->load->model('m_category');
        $this->load->model('m_app_version');
        $this->load->model('m_platform');
    }

    function index($del_noti = '')
    {
        $this->load->library('pagination');
        $offset = $this->input->get('offset', 0);
        $cate = $this->input->get('cate') ? $this->input->get('cate') : -1;
        $status = $this->input->get('status') !== FALSE ? $this->input->get('status') : -1;
        $limit = 20;

        $where = array();
        if ($cate != -1)
            $where['category.cate_id'] = $cate;
        if ($status != -1)
            $where['apps.app_status'] = $status;

        $url = current_url() . "?cate=$cate&status=$status";
        $config = array();
        $config['base_url'] = $url;
        $config['total_rows'] = count($this->m_app->multi_select($where));
        $config['per_page'] = $limit;
        $config['query_string_segment'] = 'offset';
        $config['page_query_string'] = TRUE;

        $this->pagination->initialize($config);
        $this->set_var('paging', $this->pagination->create_links());

        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";

        $this->set_var('items', $this->m_app->multi_select($where, 'app_rank DESC, apps.app_id DESC', $limit, $offset));
        $this->set_var('category', $this->m_category->multi_select());
        $this->set_var('cate_select_box', $this->_cate_select_box($this->data['category'], $cate));
        $this->set_var('title', 'Danh sách ứng dụng');
        if ($del_noti != '')
            $this->set_var('del_noti', 'Xóa ứng dụng có ID: ' . $del_noti);
        $this->view('apps/index');
    }

    function search()
    {
        $this->load->library('pagination');

        $offset = $this->input->get('offset', 0);
        $limit = 20;

        $search = array();
        $where = array();
        if ($this->input->get('s') != '')
            $search['app_name'] = $this->input->get('s');

        $url = current_url() . "?s=" . $search['app_name'];
        $config = array();
        $config['base_url'] = $url;
        $config['total_rows'] = count($this->m_app->search($search, $where));
        $config['per_page'] = 20;
        $config['page_query_string'] = TRUE;
        $config['query_string_segment'] = 'offset';
        $config['first_link'] = 'Trang đầu';
        $config['last_link'] = 'Trang cuối';

        $this->pagination->initialize($config);
        $this->set_var('paging', $this->pagination->create_links());

        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";

        $this->set_var('items', $this->m_app->search($search, $where, '', $limit, $offset));
        $this->set_var('category', $this->m_category->multi_select());
        $this->set_var('title', 'Tìm kiếm');
        $this->view('apps/index');
    }

    function up_hot($id = FALSE)
    {
        if (!$id)
            redirect('apps');

        $item = $this->m_app->select_one(array('apps.app_id' => $id));

        if (!$item)
            redirect('apps');

        if ($item['app_rank'] == 0)
            $this->m_app->update(array('apps.app_id' => $id), array('app_rank' => 1));
        else
            $this->m_app->update(array('apps.app_id' => $id), array('app_rank' => 0));

        redirect('apps');
    }

    function sort_hot()
    {
        $rank_array = $this->input->post('rank');

        $rank_array = explode(',', $rank_array);

        $new_array = array();
        if (empty($rank_array))
            exit('ERROR');

        foreach ($rank_array as $rank => $id)
        {
            if ($id == '')
                continue;

            $new_array[] = $id;
        }

        if (empty($new_array))
            exit('ERROR');

        $total = count($new_array);
        foreach ($new_array as $rank => $id)
            if (!$this->m_app->update(array('apps.app_id' => $id), array('app_rank' => $total - $rank)))
                exit('ERROR');
    }

    function form($id = FALSE)
    {
        $this->load->helper('number');
        $this->set_var('title', 'Tạo ứng dụng');
        if ($id)
            $this->set_var('title', 'Sửa ứng dụng');

        $item = $this->m_app->select_one(array('apps.app_id' => $id));

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        $this->form_validation->set_rules('app_name', 'Tên ứng dụng', 'required');
        $this->form_validation->set_rules('app_cate', 'Danh mục ứng dụng', 'required');
        $this->form_validation->set_rules('app_version', 'Phiên bản', 'required');
        $this->form_validation->set_rules('app_summary', 'Tóm tắt app', 'required');
        $this->form_validation->set_rules('app_url', 'URL', "required|callback_check_app[$id]");
        $this->form_validation->set_rules('app_seo', 'SEO', 'required');
        $this->form_validation->set_rules('app_status', 'Trạng thái', 'required');
        $this->form_validation->set_rules('app_rank', 'Thứ tự', 'required');

        if ($this->input->post())
            if ($this->form_validation->run() == FALSE)
                _jsonout(FALSE, 'custom', validation_errors('<h4 class="alert_error">', '</h4>'));
            else
                $this->_save($id);

        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";
        $this->_plugins[] = "jquery_form";
        $this->_js[] = "upload";

        $this->set_var('item', $item);
        $this->set_var('platforms', $this->m_platform->multi_select());
        $category = $this->m_category->multi_select();
        $app_cate = $this->m_app_cate->multi_select(array('app_id' => $id));
        $in_cate = array();
        if ($app_cate)
        {
            foreach ($app_cate as $ac)
            {
                $in_cate[] = $ac['cate_id'];
            }
        }
        $this->set_var('cate_tree', $this->_cate_tree($category, 'input', $in_cate));
        $this->set_var('in_cate', $in_cate);
        $this->set_var('app_file', $this->m_app_version->multi_select(array('app_id' => $id)));
        $this->set_var('id', $id);

        $this->view('apps/form');
    }

    private function _save($id = FALSE)
    {
        $data = array();
        $data['pf_id'] = intval($this->input->post('pf_id'));
        $data['app_name'] = trim($this->input->post('app_name'));
        $data['app_version'] = trim($this->input->post('app_version'));
        $data['app_size'] = trim($this->input->post('app_size'));
        $data['app_name_url'] = trim($this->input->post('app_url'));
        $data['app_summary'] = trim($this->input->post('app_summary'));
        $data['app_desc'] = trim($this->input->post('app_desc'));
        $data['app_seo'] = trim($this->input->post('app_seo'));
        $data['app_price'] = trim($this->input->post('app_price'));
        $data['app_thumb'] = trim($this->input->post('app_thumb'));
        $data['app_rank'] = intval($this->input->post('app_rank'));
        $data['app_status'] = intval($this->input->post('app_status'));
        $data['app_eid'] = $this->input->post('app_eid');
        $data['app_vote_total'] = $this->input->post('app_vote_total');
        $data['app_vote_star'] = $this->input->post('app_vote_star');
        $data['app_updated'] = time();

        // Nếu có up ảnh thumbnail
        if ($this->input->post('thumb') != '')
            $data['app_thumb'] = $this->_save_photo(array($this->input->post('thumb')), TRUE);

        // Screenshot hiện có
        $current_screenshot = @$this->input->post('current_screenshot');

        // Nếu có xóa đi ảnh screenshot nào đó
        $ss_del = @$this->input->post('screenshot_del', TRUE);
        if (!empty($ss_del))
        {
            foreach ($ss_del as $ss_file)
            {
                // Bỏ đi khỏi screenshot hiện tại
                $current_screenshot = str_replace($ss_file . ",", '', $current_screenshot);
                $current_screenshot = str_replace($ss_file, '', $current_screenshot);
                @unlink(PHOTO_DIR . $ss_file);
            }
        }

        // Nếu có thêm ảnh screenshot
        $screenshot = @$this->input->post('screenshot');
        if (!empty($screenshot))
        {
            $screenshot = $this->_save_photo($screenshot);
        }

        $current_screenshot .= ',' . $screenshot;
        $data['app_screenshot'] = trim($current_screenshot, ',');

        $data_file = $this->input->post('apps_file');
        $data_cate = $this->input->post('app_cate');
        $av_del = @$this->input->post('av_del', TRUE);
        if ($id)
        {
            if ($this->m_app->update(array('app_id' => $id), $data))
            {
                // Cập nhật thông tin vào GraphDB
                $gphdata['ita'] = 'create';
                $gphdata['itt'] = 'APP';
                $gphdata['ite'] = $data['app_eid'];
                $gphdata['itn'] = $data['app_name'];
                $gphdata['ipr'] = $data['app_price'];
                $gphdata['ith'] = $data['app_thumb'];
                $gphdata['ips'] = $data['app_status'];
                $this->graph_update($gphdata);

                $solr_data = $this->solr_data_from_post_data($data);
                $this->solr_update($id, $solr_data);
                try
                {
                    $this->_save_file($id, $data_file);
                    $this->_save_cate($id, $data_cate);
                    $this->_del_file($av_del);
                }
                catch (Exception $exc)
                {
                    _jsonout(TRUE, 'error', $exc->getTraceAsString());
                }

                _jsonout(TRUE, 'success', "Cập nhật ứng dụng thành công!");
            }
            else
                _jsonout(FALSE, 'error', "Không cập nhật được ứng dụng!");
        }

        $respone = @file_get_contents(CREATE_EID_API);
        $result = @json_decode($respone);
        $eid = @$result->params->alphaId;

        if ($eid != '')
            $data['app_eid'] = $eid;
        $data['app_created'] = time();
        $data['app_fake_downloads'] = rand(APP_MIN_FAKE_DOWNLOADS, APP_MAX_FAKE_DOWNLOADS);
        $insert_id = $this->m_app->insert($data);
        $solr_data = $this->solr_data_from_post_data($data);
        $this->solr_update($insert_id, $solr_data);

        // Cập nhật thông tin vào GraphDB
        $gphdata['ita'] = 'create';
        $gphdata['itt'] = 'APP';
        $gphdata['ite'] = $data['app_eid'];
        $gphdata['itn'] = $data['app_name'];
        $gphdata['ipr'] = $data['app_price'];
        $gphdata['ith'] = $data['app_thumb'];
        $gphdata['ips'] = $data['app_status'];
        $this->graph_update($gphdata);

        if ($insert_id)
        {
            try
            {
                $this->_save_file($insert_id, $data_file);
                $this->_save_cate($insert_id, $data_cate);
            }
            catch (Exception $exc)
            {
                _jsonout(FALSE, 'error', $exc->getTraceAsString());
            }

            _jsonout(TRUE, 'success', "Tạo ứng dụng thành công!");
        }
        else
            _jsonout(FALSE, 'error', "Không tạo được ứng dụng!");
    }

    private function _del_file($av_del)
    {
        if (!empty($av_del))
            foreach ($av_del as $av_id)
            {
                $av = $this->m_app_version->select_one(array('av_id' => $av_id));
                if (file_exists($av['av_file']))
                {
                    $path_parts = pathinfo($av['av_file']);
                    if (is_dir($path_parts['dirname']))
                    {
                        $this->load->helper('file');
                        delete_files($path_parts['dirname'], TRUE);
                        rmdir($path_parts['dirname']);
                    }
                }
                $this->m_app_version->delete(array('av_id' => $av_id));
            }
    }

    private function _save_file($app_id, $data_file)
    {
        if (!$app_id)
            return;

        if (empty($data_file))
            return;

        foreach ($data_file as $row)
        {
            if (!$row['av_file'])
                continue;

            if (!isset($row['av_dir']) OR $row['av_dir'] == '')
                continue;

            $sav_dir = '/' . date('Y/md', time()) . '/' . $row['av_dir'];
            $today_dir = UPLOAD_DIR . $sav_dir;

            if (!is_dir($today_dir))
                mkdir($today_dir, 0777, TRUE);

            $av_file = '';
            if (isset($row['av_file']) && $row['av_file'] != '')
            {
                $av_file = $row['av_file'];
                if (file_exists($av_file))
                {
                    if (!file_exists($today_dir . '/' . basename($av_file)))
                        rename($av_file, $today_dir . '/' . basename($av_file));

                    $av_file = $sav_dir . '/' . basename($av_file);
                }
                else
                    $av_file = '';
            }

            if (isset($row['av_file2']) && $row['av_file2'] != '')
                if (file_exists($row['av_file2']))
                    if (!file_exists($today_dir . '/' . basename($row['av_file2'])))
                        rename($row['av_file2'], $today_dir . '/' . basename($row['av_file2']));

            $data = array(
                'app_id' => $app_id,
                'av_file' => ($av_file != '') ? nice_url($av_file) : '',
                'av_size' => isset($row['av_size']) ? $row['av_size'] : '',
                'av_phone' => isset($row['av_phone']) ? $row['av_phone'] : '',
                'av_os_version' => isset($row['av_os_version']) ? $row['av_os_version'] : '',
                'av_resolution_width' => isset($row['av_resolution_width']) ? $row['av_resolution_width'] : '',
                'av_resolution_height' => isset($row['av_resolution_height']) ? $row['av_resolution_height'] : '',
                'av_cldc' => isset($row['av_cldc']) ? $row['av_cldc'] : '',
                'av_midp' => isset($row['av_midp']) ? $row['av_midp'] : '',
                'av_updated' => time(),
                'av_status' => 1,
            );
            if (isset($row['av_id']))
                $this->m_app_version->update(array('av_id' => $row['av_id']), $data);
            else
            {
                $data['av_created'] = time();
                $this->m_app_version->insert($data);
            }
        }
    }

    private function _save_cate($app_id, $cate_arr)
    {
        if ($app_id)
            if (!empty($cate_arr))
            {
                $this->m_app_cate->delete(array('app_id' => $app_id));

                foreach ($cate_arr as $cate)
                    $this->m_app_cate->insert(array('app_id' => $app_id, 'cate_id' => $cate));
            }
    }

    public function delete($id = FALSE)
    {
        $app = $this->m_app->select_one(array('app_id' => $id));
        if (!$app)
            show_404();
        
        $this->m_app->delete(array('app_id' => $id));

        // Xóa thông tin ra khỏi GraphDB
        $gphdata['ita'] = 'delete';
        $gphdata['itt'] = 'APP';
        $gphdata['ite'] = $app['app_eid'];
        $this->graph_update($gphdata);

        $this->solr_del($id);

        redirect("apps/index/$id");
    }

    function category($offfset = 0, $limit = 10, $noti_del = FALSE)
    {
        $category = $this->m_category->multi_select();

        $this->load->library('pagination');

        $config = array();
        $config['base_url'] = site_url('apps/category');
        $config['total_rows'] = count($category);
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $this->set_var('paging', $this->pagination->create_links());


        $this->set_var('items', $this->m_category->multi_select(array(), 'cate_rank, cate_id DESC', $limit, $offfset));
        $this->set_var('cate_tree', $this->_cate_tree($category));
        if ($noti_del)
            $this->set_var('noti', 'Xóa danh mục thành công!');
        $this->set_var('title', 'Danh mục ứng dụng');
        $this->view('apps/category');
    }

    function category_form($id = FALSE)
    {
        $this->set_var('title', 'Thêm danh mục ứng dụng');
        if ($id)
            $this->set_var('title', 'Sửa danh mục ứng dụng');

        $item = $this->m_category->select_one(array('cate_id' => $id));

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        $this->form_validation->set_rules('cate_name', 'Tên nhóm', "required|min_length[5]|max_length[120]");
        if ($id)
            $this->form_validation->set_rules('cate_url', 'URL', 'required');
        else
            $this->form_validation->set_rules('cate_url', 'URL', 'required|callback_check_cate');
        $this->form_validation->set_rules('cate_status', 'Trạng thái', 'required');
        $this->form_validation->set_rules('cate_parent', 'Thư mục cha', 'required');
        $this->form_validation->set_rules('cate_seo', 'SEO', 'required');

        if ($this->input->post())
            if ($this->form_validation->run() == FALSE)
                _jsonout(TRUE, 'custom', validation_errors('<h4 class="alert_error">', '</h4>'));
            else
                $this->_category_save($id);

        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";
        $this->_plugins[] = "jquery_form";
        $this->_js[] = "upload";

        $this->set_var('item', $item);
        $this->set_var('cates', $this->m_category->multi_select());
        $this->set_var('cate_select_box', $this->_cate_select_box($this->data['cates'], @$item['cate_parent']));
        $this->set_var('id', $id);
        $this->view('apps/category_form');
    }

    private function _category_save($id = FALSE)
    {
        $data = array();
        $data['cate_name'] = trim($this->input->post('cate_name'));
        $data['cate_desc'] = trim($this->input->post('cate_desc'));
        $data['cate_seo'] = trim($this->input->post('cate_seo'));
        $data['cate_url'] = trim($this->input->post('cate_url'));
        $data['cate_parent'] = intval($this->input->post('cate_parent'));
        $data['cate_status'] = intval($this->input->post('cate_status'));
        $data['cate_rank'] = intval($this->input->post('cate_rank'));
        $data['cate_updated'] = time();

        // Nếu có up ảnh thumbnail
        $data['cate_thumb'] = trim($this->input->post('cate_thumb'));
        if ($this->input->post('thumb') != '')
            $data['cate_thumb'] = $this->_save_photo(array($this->input->post('thumb')), TRUE);

        if ($id)
            if ($this->m_category->update(array('cate_id' => $id), $data))
                _jsonout(TRUE, 'success', "Cập nhật danh mục ứng dụng thành công!");
            else
                _jsonout(FALSE, 'error', "Không cập nhật được danh mục ứng dụng!");

        $data['cate_created'] = time();
        if ($this->m_category->insert($data))
            _jsonout(TRUE, 'success', "Tạo danh mục ứng dụng thành công!");
        else
            _jsonout(FALSE, 'error', "Không tạo được danh mục ứng dụng!");
    }

    public function category_delete($id = FALSE)
    {
        if ($id)
            $this->m_category->delete(array('cate_id' => $id));

        redirect('apps/category/0/20/noti_del');
    }

    function upload_app()
    {
        $this->load->helper('number');
        $temp_dir = 'assets/upload/temp/';
        $temp_zip = 'assets/upload/temp/' . time();
        $config = array();
        $config['upload_path'] = "./$temp_dir";
        $config['allowed_types'] = 'zip';
        $config['max_size'] = '0';
        $config['max_width'] = '0';
        $config['max_height'] = '0';

        $this->load->library('upload', $config);

        if ($this->upload->do_upload())
        {
            $file = $this->upload->data();

            $zip_file = $file['full_path'];

            $zip = new ZipArchive;
            if ($zip->open($zip_file) === TRUE)
            {
                $zip->extractTo($temp_zip);
                $zip->close();

                $this->load->helper('directory');
                $map = directory_map($temp_zip, FALSE, TRUE);

                $data_out = "";
                foreach ($map as $a_name => $a_dir)
                {
                    foreach ($a_dir as $name => $dir)
                    {
                        $app_file1 = '';
                        $app_file_full_1 = '';
                        $app_file2 = '';
                        $app_file_full_2 = '';
                        $app_phone = '';
                        $app_os = '';
                        $phone_list = '';
                        $os_list = '';
                        $cldc = '';
                        $midp = '';

                        while ($el = array_pop($dir))
                        {
                            if ($el == null)
                                break;

                            if ($el == 'phonelist.txt')
                            {
                                $phone_list = base_url() . "$temp_zip/$a_name/$name/phonelist.txt";
                                $app_phone = @file_get_contents($phone_list);
                            }
                            elseif ($el == 'oslist.txt')
                            {
                                $os_list = base_url() . "$temp_zip/$a_name/$name/oslist.txt";
                                $app_os = @file_get_contents($os_list);
                            }
                            else
                            {
                                if ($app_file1 == '')
                                {
                                    $app_file1 = $el;
                                    $app_file_full_1 = "$temp_zip/$a_name/$name/$el";
                                }
                                elseif ($app_file2 == '')
                                {
                                    $app_file2 = $el;
                                    $app_file_full_2 = "$temp_zip/$a_name/$name/$el";

                                    // File 2 phải có tên giống file 1, khác ext
                                    // Lấy tên của file 1
                                    $path_parts1 = pathinfo($app_file_full_1);
                                    $filename1 = $path_parts1['filename'];
                                    $ext1 = $path_parts1['extension'];

                                    // Lấy ext của file 2
                                    $path_parts2 = pathinfo($app_file_full_2);
                                    $ext2 = $path_parts2['extension'];

                                    // Ghép chúng lại với nhau
                                    $new_file = "$temp_zip/$a_name/$name/$filename1.$ext2";
                                    if (!file_exists($new_file))
                                        rename($app_file_full_2, $new_file);

                                    $app_file_full_2 = $new_file;

                                    if ($cldc == '' or $midp == '')
                                    {
                                        $jad_path = '';
                                        if ($ext1 == 'jad')
                                            $jad_path = base_url() . $app_file_full_1;

                                        if ($ext2 == 'jad')
                                            $jad_path = base_url() . $app_file_full_2;

                                        if ($jad_path != '')
                                        {
                                            $jad_info = $this->read_jad($jad_path);
                                            $cldc = @$jad_info['cldc'];
                                            $midp = @$jad_info['midp'];
                                        }
                                    }
                                }
                            }
                        }

                        $resolution = explode("x", $name);
                        $weight = isset($resolution[0]) ? $resolution[0] : '';
                        $height = isset($resolution[1]) ? $resolution[1] : '';

                        $data_out .= "<tr id='av_$name'>";
                        $data_out .= "<td>";
                        $data_out .= "<b>$app_file1</b>";
                        $data_out .= "<input type='hidden' value='$app_file_full_1' name='apps_file[$name][av_file]'/>";
                        $data_out .= "<input type='hidden' value='$app_file_full_2' name='apps_file[$name][av_file2]'/>";
                        $data_out .= "<input type='hidden' value='$a_name/$name/' name='apps_file[$name][av_dir]'/>";
                        $data_out .= "</td>";
                        $data_out .= "<td>";
                        $data_out .= byte_format(filesize($app_file_full_1));
                        $data_out .= "<input type='hidden' value='" . filesize($app_file_full_1) . "' name='apps_file[$name][av_size]'/>";
                        $data_out .= "</td>";
                        $data_out .= "<td>";
                        $data_out .= "<textarea rows='5' name='apps_file[$name][av_phone]'>$app_phone</textarea>";
                        $data_out .= "</td>";
                        $data_out .= "<td>";
                        $data_out .= "<textarea rows='5' name='apps_file[$name][av_os_version]'>$app_os</textarea>";
                        $data_out .= "</td>";
                        $data_out .= "<td>";
                        $data_out .= "<input type='text' size='5' name='apps_file[$name][av_resolution_width]' value='$weight' />";
                        $data_out .= "<input type='text' size='5' name='apps_file[$name][av_resolution_height]' value='$height' />";
                        $data_out .= "</td>";
                        $data_out .= "<td>";
                        $data_out .= "<input type='text' size='5' name='apps_file[$name][av_cldc]' value='$cldc' /><br/>";
                        $data_out .= "<input type='text' size='5' name='apps_file[$name][av_midp]' value='$midp' />";
                        $data_out .= "</td>";
                        $data_out .= "<td>";
                        $data_out .= "<a href='#' onclick='if(confirm(\"Bạn có chắc là muốn xóa phần tử này không?\")) $(\"#av_$name\").remove(); return false;'>Xóa</a>";
                        $data_out .= "</td>";
                        $data_out .= "</tr>";
                    }
                }
                _jsonout(true, "<h3 class='alert_success'>Upload thành công!<h3/>", $data_out);
            }
            else
                _jsonout(false, "<h3 class='alert_error'>Không đọc được file zip<h3/>");
        }
        else
            _jsonout(false, "<h3 class='alert_error'>" . $this->upload->display_errors() . "<h3/>");
    }

    private function read_jad($jad_path)
    {
        if ($jad_path == '')
            return FALSE;

        $file_info = @file_get_contents($jad_path);

        if ($file_info == '')
            return FALSE;

        $line_info = explode("\n", $file_info);

        $jad_info = array();
        foreach ($line_info as $line)
        {
            if ($line == "")
                continue;

            $info = explode(":", $line);

            $key = trim($info[0]);
            $val = trim($info[1]);

            $jad_info[$key] = $val;
            switch ($key)
            {
                case 'MicroEdition-Profile':
                    $jad_info['midp'] = $val;
                    break;
                case 'MicroEdition-Configuration':
                    $jad_info['cldc'] = $val;
                    break;
                default:
                    break;
            }
        }
        return $jad_info;
    }

    function upload_photo()
    {
        $config = array();
        $icon_dir = 'assets/upload/photo/';
        $config['upload_path'] = $icon_dir;
        $config['allowed_types'] = 'png|jpg|gif|PNG|JPG|GIF';
        $config['max_size'] = '10000';
        $config['max_width'] = '10000';
        $config['max_height'] = '10000';

        $this->load->library('upload', $config);

        if ($this->upload->do_upload())
        {
            $data = $this->upload->data();
            $img = $icon_dir . $data['file_name'];
            $img_url = base_url() . $icon_dir . $data['file_name'];
            $data_out = "<span onclick='if(confirm(\"Bạn muốn xóa ảnh này?\")) $(this).remove(); return false;'>";
            $data_out .= "<img src='$img_url' style='max-height:128px;max-width:128px'/>";
            $data_out .= "<input type='hidden' value='$img' name='screenshot[]'/>";
            $data_out .= "</span>";
            _jsonout(TRUE, "<h3 class='alert_success'>Upload thành công!<h3/>", $data_out);
        }
        else
            _jsonout(FALSE, "<h3 class='alert_error'>" . $this->upload->display_errors() . "<h3/>");
    }

    function upload_thumb()
    {
        $config = array();
        $icon_dir = 'assets/upload/photo/'; 
        $config['upload_path'] = $icon_dir;
        $config['allowed_types'] = 'png|jpg|gif|PNG|JPG|GIF';
        $config['max_size'] = '10000';
        $config['max_width'] = '10000';
        $config['max_height'] = '10000';

        $this->load->library('upload', $config);

        if ($this->upload->do_upload())
        {
            $data = $this->upload->data();
            $img = $icon_dir . $data['file_name'];
            $img_url = base_url() . $icon_dir . $data['file_name'];
            $data_out = "<span>";
            $data_out .= "<img src='$img_url' style='max-height:128px;max-width:128px'/>";
            $data_out .= "<input type='hidden' value='$img' name='thumb'/>";
            $data_out .= "</span>";
            _jsonout(TRUE, "<h3 class='alert_success'>Upload thành công!<h3/>", $data_out);
        }
        else
            _jsonout(FALSE, "<h3 class='alert_error'>" . $this->upload->display_errors() . "<h3/>");
    }
    

    function comment()
    {
        $this->load->model('m_comment');
        $this->set_var('items', $this->m_comment->multi_select());
        $this->set_var('title', 'Danh sách ứng dụng');
        $this->view('apps/comment');
    }

    private function _cate_tree($category = array(), $display = '', $in_cate = array(), $parent = 0)
    {
        if ($display == 'input')
            $tree = '<ul style="list-style: none">';
        else
            $tree = '<ul>';
        foreach ($category as $cate)
        {
            if ($cate['cate_parent'] == $parent)
            {
                $tree .= '<li>';
                if ($display == 'input')
                {
                    $tree .= "<input type='checkbox' name='app_cate[]' value='" . $cate['cate_id'] . "'";
                    if (in_array($cate['cate_id'], $in_cate))
                        $tree .= ' checked="checked"';
                    $tree .= "/>";
                }
                $tree .= $cate['cate_name'];
                $tree .= '</li>';
                $tree .= $this->_cate_tree($category, $display, $in_cate, $cate['cate_id']);
            }
        }
        $tree .= '</ul>';
        if ($tree == '<ul></ul>')
            return '';
        return $tree;
    }

    private function _cate_select_box($category = array(), $sl_cate = '', $parent = 0, $space = '')
    {
        $tree = '';
        foreach ($category as $cate)
        {
            if ($cate['cate_parent'] == $parent)
            {
                $tree .= "\t<option ";
                $tree .= "value='" . $cate['cate_id'] . "'";
                if ($cate['cate_id'] == $sl_cate)
                    $tree .= ' selected="selected"';
                $tree .= ">";
                $tree .= $space . ' ' . $cate['cate_name'];
                $tree .= "</option>\n";
                $tree .= $this->_cate_select_box($category, $sl_cate, $cate['cate_id'], $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }
        return $tree;
    }

    function check_cate($cate_url)
    {
        if ($this->m_category->select_one(array('cate_url' => $cate_url)) != FALSE)
        {
            $this->form_validation->set_message('check_cate', "%s $cate_url đã được sử dụng");
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    function check_app($url, $id = 0)
    {
        $app = $this->m_app->select_one(array('app_name_url' => $url));
        if ($app != FALSE)
        {
            if ($app['app_id'] == $id)
                return TRUE;

            $this->form_validation->set_message('check_app', "%s $url đã được sử dụng trong một ứng dụng khác.");
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    function solr_data_from_post_data($post_data)
    {
        $solr_doc_keys = array('eid', 'thumb', 'name', 'description', 'summary', 'cat', 'size', 'price', 'downloads', 'views', 'vote_total', 'vote_star', 'name_url', 'status', 'rank', 'version', 'seo', 'platform');
        $solr_data = array();
        foreach ($solr_doc_keys as $key)
        {
            if ($key == "description")
                $key = "desc";
            if (isset($post_data['app_' . $key]))
                $value = $post_data['app_' . $key];
            else
                $value = '';
            switch ($key)
            {
                case "desc":
                    $key = "description";
                    break;
                case "downloads":
                case "views":
                case "rank":
                    $value = intval($value);
                    break;
                default:
                    break;
            }
            if ($value != NULL)
                $solr_data[$key] = $value;
        }
        //log_message('debug', $solr_data["updated"]);
        return $solr_data;
    }
}
/**
 * End file app
 */
    
